const LOGIN_SUCCESS_CHANNEL = 'LOGIN_SUCCESS_CHANNEL';

export default function useBroadcast() {
  let broadcastChannel: BroadcastChannel | null = null;

  if (window.BroadcastChannel) {
    broadcastChannel = new BroadcastChannel(LOGIN_SUCCESS_CHANNEL);
  }

  const wait = () => {
    return new Promise(resolve => {
      if (broadcastChannel) {
        broadcastChannel.addEventListener('message', e => {
          resolve(e.data);
        });
      } else {
        window.addEventListener('storage', e => {
          if (e.key === LOGIN_SUCCESS_CHANNEL) {
            resolve(e.newValue ? JSON.parse(e.newValue) : null);
          }
        });
      }
    });
  };

  const send = (data: any) => {
    if (broadcastChannel) {
      broadcastChannel.postMessage(data);
    } else {
      localStorage.setItem(LOGIN_SUCCESS_CHANNEL, JSON.stringify(data));
    }
  };

  const clear = () => {
    if (broadcastChannel) {
      broadcastChannel.close();
      broadcastChannel = null;
    } else {
      localStorage.removeItem(LOGIN_SUCCESS_CHANNEL);
    }
  };

  return { send, wait, clear };
}
